package com.pangu.core.engine.game.task.zhajinhua;

import java.util.Date;

import org.cache2k.expiry.ValueWithExpiryTime;

import com.pangu.core.BMDataContext;
import com.pangu.core.cache.CacheHelper;
import com.pangu.core.engine.game.ActionTaskUtils;
import com.pangu.core.engine.game.BeiMiGameEvent;
import com.pangu.core.engine.game.BeiMiGameTask;
import com.pangu.core.engine.game.model.Summary;
import com.pangu.core.engine.game.task.AbstractTask;
import com.pangu.util.GameUtils;
import com.pangu.util.TimeUtil;
import com.pangu.util.rules.model.Board;
import com.pangu.util.rules.model.ZhajinhuaTakeCards;
import com.pangu.web.model.GameRoom;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * Description:结算红黑，数据存数据库
 *
 * @author abo
 * @date 2018年4月4日
 */
@Slf4j
public class CreateZhajinhuaAllCardsTask extends AbstractTask implements ValueWithExpiryTime, BeiMiGameTask {

	private long timer;
	private GameRoom gameRoom = null;
	private String orgi;

	public CreateZhajinhuaAllCardsTask(long timer, GameRoom gameRoom, String orgi) {
		super();
		this.timer = timer;
		this.gameRoom = gameRoom;
		this.orgi = orgi;
	}

	@Override
	public long getCacheExpiryTime() {
		return System.currentTimeMillis() + timer * 1000; // 5秒后执行
	}

	public void execute() {
		// 结算并且保存记录
		Board board = (Board) CacheHelper.getBoardCacheBean().getCacheObject(gameRoom.getId(), gameRoom.getOrgi());
		Summary summary = board.summary(board, gameRoom, gameRoom.getGamePlayway());
		// 通知所有客户端结束牌局，进入结算
		sendEvent("settlement", summary, gameRoom);
		// 删除之前的board和下注记录
		BMDataContext.getZhajinhuaEngine().finished(gameRoom.getId(), orgi);
		log.info("---------结算完成，游戏结束等待" + BMDataContext.RESET_WAIT_TIME + "秒数开局----------");
		// 把下次房间开始时间发给前端
		String timeoutStr = TimeUtil.getDateString(new Date(), null, null, null, null, null,
				BMDataContext.RESET_WAIT_TIME, TimeUtil.PATTERN_STANDARD);
		ZhajinhuaTakeCards zhajinhuaTakeCards = new ZhajinhuaTakeCards();
		zhajinhuaTakeCards.setTimeoutStr(timeoutStr);
		ActionTaskUtils.sendEvent("resetwaittime", zhajinhuaTakeCards, gameRoom);
		// 调用状态机开始下一轮游戏
		GameUtils.getGame(gameRoom.getPlayway(), orgi).change(gameRoom, BeiMiGameEvent.ENTER.toString(),
				BMDataContext.RESET_WAIT_TIME);
	}
}
